package uk.me.dewi.appenin.android;

import uk.me.dewi.appenin.android.dao.PersonDao;
import uk.me.dewi.appenin.android.dao.PlaceDao;
import uk.me.dewi.appenin.android.dao.db.sqlite.PersonSqliteDao;
import uk.me.dewi.appenin.android.dao.db.sqlite.PlaceSqliteDao;
import uk.me.dewi.appenin.android.dao.rest.xml.PlaceXmlRestDao;
import uk.me.dewi.appenin.android.entity.Person;
import uk.me.dewi.appenin.android.entity.Place;
import uk.me.dewi.util.DataAccessException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;

public class PlaceView extends Activity {
    static final int DIALOG_EXCEPTION_ID = 0;

    private TextView mNameText;
    private TextView mDescriptionText;
    
    private PlaceDao mPlaceDao;
    
    private Long mPlaceId;
    private Place mPlace;
    
    private Long mUserId;
    private Person mUser;
    
    private String mErrorMessage;
    
    private SharedPreferences mSettings;
    private String mBaseUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mSettings = getSharedPreferences(Appenin.PREFS_NAME, 0);
        mBaseUrl = mSettings.getString(Appenin.PREF_BASE_URL, Appenin.DEFAULT_BASE_URL);
        
        mPlaceDao = new PlaceXmlRestDao(mBaseUrl); 
        
        setContentView(R.layout.place_view);
        
        mNameText = (TextView) findViewById(R.id.name);
        mDescriptionText = (TextView) findViewById(R.id.description);
      
        Button confirmButton = (Button) findViewById(R.id.confirm);
       
        mPlaceId = savedInstanceState != null ? savedInstanceState.getLong(PlaceSqliteDao.KEY_ROWID)
                                              : null;
        if (mPlaceId == null) {
            Bundle extras = getIntent().getExtras();            
            mPlaceId = extras != null ? extras.getLong(PlaceSqliteDao.KEY_ROWID) 
                                      : null;
        }        

        loadState();
        
        confirmButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                setResult(RESULT_OK);
                finish();
            }
        });
        
    }
    
    @Override
    protected void onStop(){
       super.onStop();
    
      SharedPreferences settings = getSharedPreferences(Appenin.PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putString("baseUrl", mBaseUrl);

      editor.commit();
      
    }
    
    protected Dialog onCreateDialog(int id) {
        Dialog dialog;
        switch(id) {
        case DIALOG_EXCEPTION_ID:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Error: "+mErrorMessage)
                   .setCancelable(false)
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           mErrorMessage = null;
                           dialog.dismiss();
                       }
                   });
            dialog = builder.create();
            break;
        default:
            dialog = null;
        }
        return dialog;
    }

    
    private void populateFields() {
        if (mPlace != null) {
            mNameText.setText(mPlace.mName);
            mDescriptionText.setText(mPlace.mDescription);
        }
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(PlaceSqliteDao.KEY_ROWID, mPlaceId);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        loadState();
    }
    
    private void loadState(){
        try{
            mPlace = mPlaceDao.fetchPlace(mPlaceId);
            populateFields();
        }catch(Exception e){
            Log.e("PlaceEdit", "Could not fetch Place "+mPlaceId
                    +" using "+mPlaceDao.getClass().getSimpleName(), e);
        }
    }
    
    private void createThisPlace(){
        mPlace = new Place();
        mPlace.mUser = mUser.mEmail;
        mPlace.mGeo = new GeoPoint(0,0); // TODO get geopoint from GPS
    }
    
    private void reportException(String message, Throwable e){
        Log.e("PlaceEdit", message, e);
        
        mErrorMessage = message;
        showDialog(DIALOG_EXCEPTION_ID);
    }
}
